package org.seckill.service.impl;

import org.apache.commons.collections.MapUtils;
import org.seckill.cache.RedisDao;
import org.seckill.dao.SeckillDao;
import org.seckill.dao.SuccessKillDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExcution;
import org.seckill.entity.Seckill;
import org.seckill.entity.SuccessKilled;
import org.seckill.enums.SeckillStatEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * Created by chenhui479 on 16/11/20.
 */

@Service
public class SeckillServiceImpl implements SeckillService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SeckillDao seckillDao;
    @Autowired
    private SuccessKillDao successKillDao;
    @Autowired
    private RedisDao redisDao;


    private final String slat = "sfffsfdsfsadksfjaskfksdjkfs";

    public List<Seckill> getSeckillList() {


        return seckillDao.queryALl(0, 100);
    }

    public Seckill getById(long seckiilId) {
        return seckillDao.queryById(seckiilId);
    }

    public Exposer exportSeckillUrl(long seckillId) {

        Seckill seckill = redisDao.getSeckill(seckillId);


        logger.info("exportSeckill==="+seckill.toString());

        if(seckill ==null){
             seckill = seckillDao.queryById(seckillId);
            if (seckill == null) {
                return new Exposer(false, seckillId);
            }else{
                redisDao.putSeckill(seckill);
            }
        }


        Date startTime = seckill.getStartTime();
        Date endTime = seckill.getEndTime();

        Date nowTime = new Date();
        if (nowTime.getTime() < startTime.getTime() ||
                nowTime.getTime() > endTime.getTime()) {
            return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime());
        }

        //转化特定字符
        String md5 = getMD5(seckillId);//TODO

        return new Exposer(true, md5, seckillId);
    }

    /**
     * 使用注解控制事务的优点
     * 1.开发团队明确标注事务方法的编程风格
     * 2.保证事务方法的执行时间尽可能短，不要穿插其他网络请求http／RPC
     * 3.不是所有的方法都需要事务，如只有一条修改操做，只读操做
     */
    @Transactional
    public SeckillExcution excuteSeckill(long seckillId, long userPhone, String md5) throws SeckillException, RepeatKillException, SeckillCloseException {

         if(md5==null || !md5.equals(getMD5(seckillId))){

             throw new SeckillException("seckill data rewrite");

         }

         //减库存
        Date nowTime = new Date();
        try {
            int updateCount = seckillDao.reduceNumber(seckillId, nowTime);
            if (updateCount <= 0) {
                //没有更新记录
                throw new SeckillCloseException("seckill is closed");
            } else {
                //记录购买行为
                int insertCount = successKillDao.inserSuccessKilled(seckillId, userPhone);
                if (insertCount <= 0) {
                    //重复秒杀
                    throw new RepeatKillException("seckill repeat");
                } else {
                    SuccessKilled successKilled = successKillDao.queryByIDwithSeckillId(seckillId, userPhone);
                    return new SeckillExcution(seckillId, SeckillStatEnum.SUCCESS, successKilled);
                }
            }

        }
        catch (SeckillCloseException el){
            throw el;
        }
        catch (RepeatKillException e2){
            throw  e2;
        }
        catch (Exception e){

            logger.error(e.getMessage(),e);

            throw new SeckillException("seckilll inner error"+ e.getMessage());
        }


    }


    private String getMD5(long seckillId) {

        String base = seckillId + "/" + slat;
        String md5 = DigestUtils.md5DigestAsHex(base.getBytes());

        return md5;
    }

    public SeckillExcution excuteSeckiillProcdure(long seckillId, long userPhone, String md5) throws SeckillException {

        if(md5==null || !md5.equals(getMD5(seckillId))){

            return new SeckillExcution(seckillId,SeckillStatEnum.DATA_REWRITE);

        }

        Date killTime= new Date();
        Map<String, Object> map = new HashMap();

        map.put("seckillId", seckillId);
        map.put("phone",userPhone);
        map.put("killTime",killTime);
        map.put("result",null);

        try{

            seckillDao.killByProcedure(map);
           int result =  MapUtils.getInteger(map,"result",-2);

           if(result ==1){
               SuccessKilled sk = successKillDao.queryByIDwithSeckillId(seckillId,userPhone);

               return new SeckillExcution(seckillId,SeckillStatEnum.SUCCESS, sk);

           }else{

               return  new SeckillExcution(seckillId,SeckillStatEnum.stateOf(result));
           }


        }catch (Exception e){

            e.printStackTrace();

            return  new SeckillExcution(seckillId,SeckillStatEnum.INNER_ERROR);
        }




    }
}